import hashlib

from flask import Blueprint, request, redirect, url_for, render_template
from sqlalchemy import or_

from apps.user.models import User
from ext import db

user_bp = Blueprint('user', __name__)


@user_bp.route('/')
def user_center():
    # 查询
    users = User.query.filter(User.isdelete == False).all()  # 逻辑删除
    return render_template('user/center.html', users=users)


@user_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        repassword = request.form.get('repassword')
        phone = request.form.get('phone')
        if password == repassword:
            user = User()
            user.username = username
            user.password = hashlib.sha256(password.encode('utf-8')).hexdigest()  # 加密
            user.phone = phone
            # 添加
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('user.user_center'))  # 重定向跳转
        else:
            return '密码不一致'
    return render_template('user/register.html')


@user_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # 验证 select * from user where username='xxxx';
        new_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
        user_list = User.query.filter_by(username=username)
        for u in user_list:
            if u.password == new_password:
                return redirect(url_for('user.user_center'))  # 重定向跳转
        else:
            return render_template('user/login.html', msg='用户名或者密码有误！')

    return render_template('user/login.html')


@user_bp.route('/search')
def search():
    keyword = request.args.get('search')
    # 查询
    user_list = User.query.filter(or_(User.username.contains(keyword), User.phone.contains(keyword))).all()
    return render_template('user/center.html', users=user_list)


@user_bp.route('/delete', endpoint='delete')
def user_delete():
    id = request.args.get('id')
    user = User.query.get(id)
    # 逻辑删除
    user.isdelete = True
    db.session.commit()
    return redirect(url_for('user.user_center'))


@user_bp.route('/update', methods=['POST', 'GET'], endpoint='update')
def update_user():
    if request.method == 'POST':
        username = request.form.get('username')
        phone = request.form.get('phone')
        id = request.form.get('id')
        user = User.query.get(id)
        user.phone = phone
        user.username = username
        db.session.commit()
        return redirect(url_for('user.user_center'))
    else:
        id = request.args.get('id')
        user = User.query.get(id)
        return render_template('user/update.html', user=user)


@user_bp.route('/logout', methods=['GET', 'POST'])
def logout():
    return '用户登出'

